package com.auto.survey.activity.monitoring.station

import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.auto.survey.R
import com.auto.survey.activity.monitoring.IntentKey.KEY_INTENT_STATION_ID
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.base.BaseActivity
import com.auto.survey.util.Helper
import com.auto.survey.util.monitoring.intersection.RearIntersectionAlgorithm
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 测站详情
 */
class DetailStationActivity: BaseActivity() {
    private val database = MonitoringRepository()
    override fun initView() {
        val stationId = intent.getIntExtra(KEY_INTENT_STATION_ID, -1)
        mTopBar?.visibility = View.VISIBLE
        mTopBar?.setBackgroundResource(R.color.action_bar)

        mComment_title?.visibility = View.VISIBLE
        mComment_title?.setBackgroundResource(R.color.action_bar)
        mComment_title?.setTitle("测站详情")
        val statinanme = findViewById<TextView>(R.id.tv_sd_name)
        val calculationTvRlt = findViewById<TextView>(R.id.tv_sd_caluation_result)
        val calculationTvWarn = findViewById<TextView>(R.id.tv_sd_caluation_warn)
        val calculationTvX = findViewById<TextView>(R.id.tv_sd_x)
        val calculationTvY = findViewById<TextView>(R.id.tv_sd_y)
        val calculationTvZ = findViewById<TextView>(R.id.tv_sd_z)
        val calculationroot = findViewById<LinearLayout>(R.id.ll_cs_root)
        val calculationDetil = findViewById<LinearLayout>(R.id.ll_sd_caluation_root)

        lifecycleScope.launch {
            val station = database.getStationById(stationId)
            val stationDetail = database.getCalculationStationResult(stationId)

            withContext(Dispatchers.Main){
                if (station != null) {
                    statinanme.text = station.stationName
                    calculationTvX.text = "北坐标(X)\n${Helper.formateDecimal(station.stationX)}"
                    calculationTvY.text = "东坐标(Y)\n${Helper.formateDecimal(station.stationY)}"
                    calculationTvZ.text = "高程(Z)\n${Helper.formateDecimal(station.stationZ)}"
                }

                if (stationDetail.isEmpty()) {
                    calculationroot.visibility = View.GONE
                } else {
                    calculationroot.visibility = View.VISIBLE

                    val result = stationDetail[0].result
                    val nonCompliantPoints = stationDetail[0].nonCompliantPoints
                    val verificationResults = stationDetail[0].verificationResults

                    if (result.isConverged && result.isVerificationPassed) {
                        calculationTvRlt.setTextColor(ContextCompat.getColor(this@DetailStationActivity, android.R.color.holo_green_dark))
                        calculationTvRlt.text = "成功"
                        if (result.isThirdOrderStandardMet) {
                            calculationTvWarn.visibility = View.GONE
                            Log.i("CreateStationActivity","计算结果符合三等平面控制测量标准")
                        } else {
                            calculationTvWarn.visibility = View.VISIBLE
                            calculationTvWarn.text = "警告：计算结果不符合三等标准,"
                        }
                    } else {
                        calculationTvRlt.setTextColor(ContextCompat.getColor(this@DetailStationActivity, android.R.color.holo_red_dark))
                        calculationTvRlt.text = "失败"
                    }

                    calculationDetil.removeAllViews()
                    verificationResults.forEach { verification->
                        val title = "控制点[${verification.pointName}]验证汇总:\n"
                        val vcheck = "    垂直角残差: ${Helper.degrees(verification.zenithAngleDifference)}" +
                                "（阈值: ${RearIntersectionAlgorithm.DEFAULT_ZENITH_ANGLE_THRESHOLD_SECONDS}秒）→ " +
                                "${if (verification.isZenithAnglePassed) "通过" else "失败"}\n"
                        val hcheck = "    水平距残差: ${String.format("%.6f", verification.distanceDifference)} m" +
                                "（阈值: ${RearIntersectionAlgorithm.DEFAULT_POSITION_THRESHOLD} m）→ " +
                                "${if (verification.isDistancePassed) "通过" else "失败"}\n"
                        val hzcheck = "    水平角残差: ${Helper.degrees(verification.angleDifference)}" +
                                "（阈值: ${RearIntersectionAlgorithm.DEFAULT_ANGLE_THRESHOLD_SECONDS}秒）→ " +
                                "${if (verification.isAnglePassed) "通过" else "失败"}\n"
                        val checkrlt = "    整体验证结果: ${if (verification.isAnglePassed &&
                            verification.isDistancePassed && verification.isZenithAnglePassed) "通过" else "失败"}\n"

                        val rlt = title + vcheck + hcheck + hzcheck + checkrlt

                        val rltText = TextView(this@DetailStationActivity)
                        val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                        layoutParams.gravity = Gravity.CENTER_VERTICAL
                        rltText.layoutParams = layoutParams
                        rltText.setTextColor(ContextCompat.getColor(this@DetailStationActivity, R.color.common_text_colr))
                        rltText.text = rlt
                        calculationDetil.addView(rltText)
                    }
                }

            }

        }
    }

    override fun getLayoutId(): Int {

        return R.layout.activity_station_detail
    }
}